package com.bnyy.medicalHousekeeper.moudle.health.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bnyy.bean.event.Event;
import com.bnyy.common.Constant;
import com.bnyy.common.bean.UserInfo;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.health.bean.BloodPressureWeekly;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.moudle.health.fragment.BloodPressureWeeklyFragment;
import com.bnyy.medicalHousekeeper.moudle.health.fragment.GenerateWeeklyFragment;
import com.bnyy.medicalHousekeeper.moudle.health.fragment.NoWeeklyFragment;
import com.bnyy.medicalHousekeeper.moudle.health.fragment.WaitForWeeklyFragment;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.function.Consumer;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description : 血压健康周报
 * Date : 2022/8/29
 **/
public class BloodPressureWeeklyActivity extends BaseActivityImpl
        implements GenerateWeeklyFragment.Callback,
        WaitForWeeklyFragment.Callback,
        BloodPressureWeeklyFragment.Callback {

    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.iv_man)
    ImageView ivMan;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_header)
    ScaleImageView ivHeader;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_relation)
    TextView tvRelation;
    @BindView(R.id.tv_change_device)
    TextView tvChangeDevice;
    @BindView(R.id.fl_container)
    FrameLayout flContainer;
    @BindView(R.id.tv_history)
    TextView tvHistory;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;

    private int weeklyId = -1, userId = -1;

    public static void show(Context context, int userId) {
        Intent intent = new Intent(context, BloodPressureWeeklyActivity.class);
        intent.putExtra("userId", userId);
        context.startActivity(intent);
    }

    public static void show(Context context, int userId, int weeklyId) {
        Intent intent = new Intent(context, BloodPressureWeeklyActivity.class);
        intent.putExtra("userId", userId);
        intent.putExtra("weeklyId", weeklyId);
        context.startActivity(intent);
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_health_blood_pressure_weekly;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        userId = intent.getIntExtra("userId", -1);
        weeklyId = intent.getIntExtra("weeklyId", -1);

//        ArrayList<UserInfo> allUserInfos = userInfoManager.getAllUserInfos();
//        if (allUserInfos.size() > 1) {
//            llUserInfo.setVisibility(View.VISIBLE);
//            for (UserInfo userInfo : allUserInfos) {
//                if (userInfo.getId() == userId) {
//                    setUserInfo(userInfo);
//                    break;
//                }
//            }
//        } else {
//            llUserInfo.setVisibility(View.GONE);
//        }

        GradientDrawable bg = new GradientDrawable();
        bg.setColor(Color.parseColor("#FFC54A"));
        bg.setCornerRadii(new float[]{
                360F, 360F, // 左上
                360, 360, // 右上
                360, 360,
                0F, 0F, // 左下
        });
        ;
        tvRelation.setBackground(bg);

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tvHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BloodPressureWeeklyHistoryActivity.show(mContext, userId);
            }
        });

//        tvChangeDevice.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showUsersPopupWindow();
//            }
//        });

        if (weeklyId == -1) {
            getBloodPressureWeeklyByUserId();
        } else {
            getBloodPressureWeeklyByWeeklyId();
        }

    }

    private void setUserInfo(UserInfo userInfo) {
        userId = userInfo.getId();
        if (userId == userInfoManager.getLoginUserId()) {
            tvRelation.setText("本人");
        } else {
            tvRelation.setText(userInfo.getRelationship());
        }
        tvUsername.setText(userInfo.getUsername());
        GlideHelper.setCircleImage(mContext, userInfo.getUserimg(), ivHeader, 2, Color.WHITE, R.mipmap.icon_default_header_man);
    }

    @Override
    public void onGenerateWeekly() {
        generateOrUpdateBloodPressureWeekly(new BaseObserverImpl<Object>(mContext) {
            @Override
            public void onSuccess() {
                super.onSuccess();
                getBloodPressureWeeklyByUserId();
            }

            @Override
            public void onOtherCode(int code) {
                super.onOtherCode(code);

//                if (code == 11004) {
//                    BloodPressureQuestionnaireActivity.show(mContext, requestManager.getBaseUrl() + "html/h5/#/healthQuestionnaire?userId=" + userId);
//                }
            }
        });
    }

    @Override
    public void onConfirm() {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event eventBusBean) {
        if (eventBusBean.getTag() instanceof Integer) {
            if ((int) eventBusBean.getTag() == Constant.EventBusTag.QUESTIONNAIRE_FINISH) {
                onGenerateWeekly();
            }
        }
    }

    private void getBloodPressureWeeklyByUserId() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        getBloodPressureWeekly(params);
    }

    private void getBloodPressureWeeklyByWeeklyId() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", weeklyId);
        getBloodPressureWeekly(params);
    }

    private void getBloodPressureWeekly(HashMap<String, Object> params) {
        requestManager.request(requestManager.mHealthDataRetrofitService.getBloodPressureWeekly(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<BloodPressureWeekly>(mContext) {
                    @Override
                    public void onSuccess(BloodPressureWeekly bloodPressureWeekly) {
                        super.onSuccess(bloodPressureWeekly);
                        llDate.setVisibility(View.GONE);

                        boolean readOnly = true;

//                        for (User.DeviceUserInfo deviceUserInfo : userInfoManager.getOwnerDeviceUserInfos()) {
//                            if (deviceUserInfo.getUser().getId() == userId) {
//                                readOnly = false;
//                                break;
//                            }
//                        }
                        bloodPressureWeekly.setReadOnly(readOnly);

                        int status = bloodPressureWeekly.getStatus();
                        if (status != 1) {
                            showFragment(new NoWeeklyFragment());
                        } else {
                            switch (status) {
                                case 1:
                                    llDate.setVisibility(View.VISIBLE);
                                    String startDatetime = bloodPressureWeekly.getStart_datetime();
                                    String endDatetime = bloodPressureWeekly.getEnd_datetime();
                                    SimpleDateFormat sdfYMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        Calendar calendar = Calendar.getInstance();

                                        calendar.setTime(sdfYMDHMS.parse(startDatetime));
                                        int fromYear = calendar.get(Calendar.YEAR);
                                        int fromMonth = calendar.get(Calendar.MONTH) + 1;
                                        int fromDay = calendar.get(Calendar.DAY_OF_MONTH);

                                        calendar.setTime(sdfYMDHMS.parse(endDatetime));
                                        int toYear = calendar.get(Calendar.YEAR);
                                        int toMonth = calendar.get(Calendar.MONTH) + 1;
                                        int toDay = calendar.get(Calendar.DAY_OF_MONTH);

                                        StringBuilder sb = new StringBuilder();
                                        sb.append(fromYear)
                                                .append("年")
                                                .append(fromMonth)
                                                .append("月")
                                                .append(fromDay)
                                                .append("日")
                                                .append("至");

                                        if (fromYear == toYear) {
                                            if (fromMonth != toMonth) {
                                                sb.append(toMonth).append("月");
                                            }
                                            sb.append(toDay).append("日");
                                        } else {
                                            sb.append(toYear)
                                                    .append("年")
                                                    .append(toMonth)
                                                    .append("月")
                                                    .append(toDay)
                                                    .append("日");
                                        }
                                        tvDate.setText(sb.toString());
                                        tvShare.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
//                                                userInfoManager.getAllUserInfos().forEach(new Consumer<UserInfo>() {
//                                                    @Override
//                                                    public void accept(UserInfo userInfo) {
//                                                        if (userInfo.getId() == userId) {
//                                                            BloodPressureWeeklyShareActivity.show(mContext, bloodPressureWeekly, userInfo);
//                                                        }
//                                                    }
//                                                });
                                            }
                                        });
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    showFragment(BloodPressureWeeklyFragment.getInstance(bloodPressureWeekly, false));
                                    break;
                                case 2:
                                    showFragment(WaitForWeeklyFragment.getInstance(bloodPressureWeekly.getHwr_phrase()));
                                    break;
                                case 3:
                                    showFragment(new GenerateWeeklyFragment());
                                    break;
                            }
                        }
                    }

                    @Override
                    public void onOtherCode(int code) {

                        llDate.setVisibility(View.GONE);
                        showFragment(new NoWeeklyFragment());

//                        if (code == 11002) {
//                            DialogHelper.showBindDeviceDialog(mContext, new DialogHelper.Callback() {
//                                @Override
//                                public void onRightClick(AlertDialog alertDialog) {
//                                    super.onRightClick(alertDialog);
//                                    finish();
//                                }
//                            });
//                        } else {
//                            super.onOtherCode(code);
//                        }
                    }
                });
    }

    private void showFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(flContainer.getId(), fragment);
        transaction.commitNowAllowingStateLoss();
    }

    @Override
    public void onUpdate(Consumer<BloodPressureWeekly> consumer) {
        generateOrUpdateBloodPressureWeekly(new BaseObserverImpl<Object>(mContext) {
            @Override
            public void onSuccess() {
                super.onSuccess();

                getBloodPressureWeeklyByUserId();

//                HashMap<String, Object> params = new HashMap<>();
//                params.put("user_id", userId);
//
//                requestManager.request(requestManager.mHealthDataRetrofitService.getBloodPressureWeekly(RequestManager.getJsonRequestBody(params)),
//                        new BaseObserverImpl<BloodPressureWeekly>(mContext) {
//                            @Override
//                            public void onSuccess(BloodPressureWeekly bloodPressureWeekly) {
//                                super.onSuccess(bloodPressureWeekly);
//                                consumer.accept(bloodPressureWeekly);
//                            }
//                        });
            }
        });
    }

    private void generateOrUpdateBloodPressureWeekly(BaseObserverImpl<Object> observer) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        requestManager.request(requestManager.mHealthDataRetrofitService.generateBloodPressureWeekly(RequestManager.getJsonRequestBody(params)), observer);
    }

    private PopupWindow popupWindow;

//    private void showUsersPopupWindow() {
//        if (popupWindow == null) {
//            popupWindow = new PopupWindow(mContext);
//            popupWindow.setWidth(ScreenUtils.getScreenWidth() / 3 * 2);
//
//            ArrayList<UserInfo> allUserInfos = userInfoManager.getAllUserInfos();
//
//            if (allUserInfos.size() > 5) {
//                popupWindow.setHeight(ScreenUtil.getScreenHeight() / 2);
//            } else {
//                popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//            }
//            View root = getLayoutInflater().inflate(R.layout.pop_win_device_list, null);
//            root.findViewById(R.id.button_manage_device).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    BaseActivity.show(mContext, DevicesManageActivity.class);
//                    popupWindow.dismiss();
//                }
//            });
//            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                @Override
//                public void onDismiss() {
//
//                }
//            });
//            ListView listView = root.findViewById(R.id.lv_device_list);
//            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    UserInfo userInfo = (UserInfo) view.getTag();
//                    if (userInfo.getId() != userId) {
//                        userId = userInfo.getId();
//                        setUserInfo(userInfo);
//                        getBloodPressureWeeklyByUserId();
//                    }
//                    popupWindow.dismiss();
//                }
//            });
//            listView.setAdapter(new BaseAdapter() {
//                @Override
//                public int getCount() {
//                    return allUserInfos.size();
//                }
//
//                @Override
//                public Object getItem(int i) {
//                    return null;
//                }
//
//                @Override
//                public long getItemId(int i) {
//                    return i;
//                }
//
//                @Override
//                public View getView(int i, View view, ViewGroup viewGroup) {
//                    View root = getLayoutInflater().inflate(R.layout.pop_win_item_home_page_select_user, viewGroup, false);
//                    UserInfo userInfo = allUserInfos.get(i);
//
//                    TextView tvUsername = root.findViewById(R.id.tv_user_name);
//                    TextView tvChange = root.findViewById(R.id.tv_change);
//                    ScaleImageView ivHeader = root.findViewById(R.id.iv_header);
//                    boolean b = userInfo.getId() == userInfoManager.getSelectedUserId();
//                    tvChange.setText(b ? "当前" : "切换");
//                    tvChange.setTextColor(Color.parseColor(b ? "#21AB38" : "#0071BD"));
//                    tvChange.setBackgroundColor(Color.parseColor(b ? "#DAF2DE" : "#FFFFFF"));
//
//                    String username = userInfo.getUsername();
//                    tvUsername.setText(username);
//
//                    Glide.with(mContext)
//                            .load(userInfo.getUserimg())
//                            .placeholder(R.mipmap.icon_default_header_man)
//                            .error(R.mipmap.icon_default_header_man)
//                            .optionalTransform(new CircleCrop())
//                            .into(ivHeader);
//                    root.setTag(userInfo);
//                    return root;
//                }
//            });
//            popupWindow.setContentView(root);
//            popupWindow.setOutsideTouchable(false);
//            popupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
////            popupWindow.setAnimationStyle(R.style.pop_add);
//            popupWindow.setFocusable(true);
//            popupWindow.setTouchable(true);
//            popupWindow.setOutsideTouchable(true);
//        }
//
//        if (popupWindow.isShowing()) {
//            popupWindow.dismiss();
//        } else {
//            PopupWindowCompat.showAsDropDown(popupWindow, tvChangeDevice, -SizeUtils.dp2px(12), SizeUtils.dp2px(12), Gravity.BOTTOM);
//        }
//    }
}



































